const axios = require('axios');
const wxConfig = require('../config/wxConfig');

/**
 * 微信API服务
 */
const wxService = {
  /**
   * 通过微信登录code获取openid
   * @param {string} code - 微信小程序登录时获取的临时code
   * @returns {Promise<Object>} 包含openid和session_key的对象
   */
  async code2Session(code) {
    try {
      const response = await axios.get(wxConfig.jscode2sessionUrl, {
        params: {
          appid: wxConfig.appId,
          secret: wxConfig.appSecret,
          js_code: code,
          grant_type: 'authorization_code'
        }
      });
      if (response.data.errcode) {
        throw new Error(`微信API错误: ${response.data.errcode} - ${response.data.errmsg}`);
      }
      
      return {
        openid: response.data.openid,
        session_key: response.data.session_key,
        unionid: response.data.unionid // 如果开发者拥有多个移动应用、网站应用、公众号、小程序，可通过unionid来区分用户的唯一性
      };
    } catch (error) {
      console.error('微信code2session请求失败:', error);
      throw error;
    }
  }
};

module.exports = wxService; 